<?php
namespace app\frontend\controller;
use think\Db;
use think\Controller;

require_once './fenci.php';
class Similarity extends Controller
{
    public $wordArr = array();
	public $strArr1 = array();
	public $strArr2 = array();
	public $vectorStr1 = array();
	public $vectorStr2 = array();
	
    //构造函数
    public function __construct($str1,$str2)
    {
		
        $this->strArr1 = explode(" ",fenci($this->delSymbol($str1)));
        $this->strArr2 = explode(" ",fenci($this->delSymbol($str2)));
		$this->wordArr = array_unique(array_merge($this->strArr1, $this->strArr2));
		$this->vectorStr1 = $this->getVectorStr($this->strArr1,$this->wordArr);
		$this->vectorStr2 = $this->getVectorStr($this->strArr2,$this->wordArr);
		
    }
	
	//计算相似度 越接近1 越相似
	public function similarity(){
		$sum = 0;
		$sumT1 = 0;
		$sumT2 = 0;
		$vectorStr1 = $this->vectorStr1;
		$vectorStr2 = $this->vectorStr2;
		foreach($this->wordArr as $key => $temp){
			$sum += $vectorStr1[$key] * $vectorStr2[$key];
			$sumT1 += pow($vectorStr1[$key],2);
			$sumT2 += pow($vectorStr2[$key],2);
		}
		$result = $sum / (sqrt($sumT1) * sqrt($sumT2));
		return $result;
	}
	
	//生成词频向量数组
	public function getVectorStr($strArr,$wordArr){
		$vectorStr = array();
		foreach($wordArr as $key1 => $temp2){
			$num = 0;
			foreach($strArr as $key2 => $temp1){
				if($temp2 == $temp1){
					$num++;
				}
			}
			$vectorStr[$key1] = $num;
		}
		return $vectorStr;
	}
	
	
	//去除字符串中的 多余符合提高准确率
	public function delSymbol($str){
        $symbolArr = array('​','“','”','"','>','<',' ',' ','`','·','~','!','！','@','#','$','￥','%','^','……',
            '&','*','(',')','（','）','-','_','——','+','=','|','\\','[',']',
            '【','】','{','}',';','；',':','：','\'','"','“','”',',','，','<','>','《','》','.','。','/','、','?','？');
        return str_replace($symbolArr,'',$str);
    }
 
}
--------------------- 
作者：晓丶峰 
来源：CSDN 
原文：https://blog.csdn.net/xf552527/article/details/65632582 
版权声明：本文为博主原创文章，转载请附上博文链接！